using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyAndSort
{

    class BucketSort : ISortStrategy
    {
        public void Sort<T>(IList<T> array, int keyNum = 0) where T : IComparable
        {
            //分配与收集操作
            for (int i = 0; i < keyNum; i++)
            {
                DistributeAndCollect(array, i);
            }
        }

        private static void DistributeAndCollect<T>(IList<T> tempList, int i) where T : IComparable
        {
            int randix = 10; //关键字取值范围
            int divider = (int)Math.Pow(10, i); //用来求得关键字数量级

            //初始化“桶”序列
            List<LinkedList<T>> bucketList = new List<LinkedList<T>>(); 
            for (int j = 0; j < randix; j++)
            {
                bucketList.Add(new LinkedList<T>());
            }

            // 开始一次分配
            while (tempList.Count != 0)
            {
                int index = ((int)(object)tempList[0]/ divider) % 10;//算出当前位上关键字的值
                //入桶
                T firstValue = tempList[0];
                tempList.RemoveAt(0);
                bucketList[index].AddLast(firstValue);
            }

            //收集桶中元素
            for (int k=0; k < randix; k++)
            {
                if (bucketList[k].First != null)
                {
                    LinkedListNode<T> nextNode = bucketList[k].First;
                    while(nextNode != null)
                    {
                        //出桶
                        bucketList[k].RemoveFirst();
                        tempList.Add (nextNode.Value);
                        nextNode = bucketList[k].First;
                    }
                }
            }
        }
    }

}
